<template>
  <div class="add-account">
    <el-dialog title="添加收款账户" center :visible.sync="addCollection" width="40%">
      <!-- <p class="tip" v-if="$store.state.user.vip == 0">您不是VIP账户 收款账户只能填写自己收款账户。开通VIP后可添加其他人收款账户！赶快去开通吧！<router-link to="/agent/vip/newVIP">开通VIP</router-link></p> -->
      <el-form :model="form" :rules="ruleForm" ref="ruleForm" label-width="120px">
        <el-form-item label="提现渠道" prop="to_type">
          <el-radio-group v-model="form.to_type" @change="toTypeChange">
            <el-radio :label="1">支付宝</el-radio>
            <el-radio :label="2">银行卡</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="账户名" prop="user_name">
          <el-input
            
            v-model="form.user_name"
            :placeholder="form.to_type == 1 ? '输入您支付宝账号绑定的身份证姓名':'输入您银行卡开户身份证的姓名'"
          ></el-input>
        </el-form-item>
        <!-- <el-form-item :label="form.to_type == 1 ? '支付宝账号' : '银行卡账号'" prop="number">
          <el-input
            v-model="form.number"
            :placeholder="form.to_type == 1 ? '请输入支付宝账号' : '请输入银行卡账号'"
          ></el-input>
        </el-form-item>-->
        <el-form-item v-if="form.to_type == 1" label="支付宝账号" prop="number">
          <el-input v-model="form.number" placeholder="请输入支付宝账号"></el-input>
        </el-form-item>
        <el-form-item v-if="form.to_type == 2" label="银行卡账号" prop="banknumber">
          <el-input v-model="form.banknumber" placeholder="请输入银行卡账号"></el-input>
        </el-form-item>
        <template v-if="form.to_type == 2">
          <el-form-item label="收款银行" prop="bank">
            <el-input v-model="form.bank" placeholder="请输入您的开户支行"></el-input>
          </el-form-item>
        </template>
        <el-form-item label="身份证号" prop="id_card">
          <el-input v-model="form.id_card" placeholder="请输入您的身份证号"></el-input>
        </el-form-item>
        <el-form-item label="身份证(正面)" prop="front_img">
          <el-upload
            class="avatar-uploader"
            :action="uploadImgUrl"
            :show-file-list="false"
            :on-success="handleSuccess1"
            :auto-upload="true"
            :before-upload="beforeUpload1"
          >
            <img v-if="frontUrl" :src="frontUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="身份证(反面)" prop="back_img">
          <el-upload
            class="avatar-uploader"
            :action="uploadImgUrl"
            :show-file-list="false"
            :on-success="handleSuccess2"
            :auto-upload="true"
            :before-upload="beforeUpload2"
          >
            <img v-if="frontUrl2" :src="frontUrl2" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="默认收款人" prop="to_payee">
          <el-radio-group v-model="form.to_payee" @change="toPayeeChange">
            <el-radio :label="1">默认</el-radio>
            <el-radio :label="2">不默认</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="合作协议" v-if="$store.state.user.role_id == 2">
          <el-checkbox class="ml10" v-model="form.isRead"></el-checkbox>我已阅读并同意
          <span style="cursor: pointer;" @click="provision">
            <font class="font_success">合作协议</font>
          </span>
          <!-- <font class="font_success">非本人</font>账户 -->
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel('ruleForm')">取 消</el-button>
        <el-button type="primary" @click="submit('ruleForm')">确 定</el-button>
      </div>
    </el-dialog>
    <agreement ref="agreement"></agreement>

    <VCCode ref="VCCode" @confirm='submitPost'/>
  </div>
</template>

<script>
import axios from "axios";
import agreement from "~/components/agreement";
import VCCode from "./VCCode";
export default {
  data() {
    var Validateid_card = function(rule, value, callback) {
      if (value === "" || value == undefined || value == null) {
        callback(new Error("请输入身份证号"));
      } else {
        if (
          !/^(^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$)|(^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])((\d{4})|\d{3}[Xx])$)$/.test(
            value
          )
        ) {
          callback(new Error("请输入正确的身份证号"));
        } else {
          callback();
        }
      }
    };
    var validatorBanknumber = function(rule, value, callback) {
      if (value === "" || value == undefined || value == null) {
        callback(new Error("请输入银行卡号"));
      } else {
        if (!/^(?:[1-9]{1})(?:\d{15}|\d{18})$/.test(value)) {
          callback(new Error("请输入正确的银行卡号"));
        } else {
          callback();
        }
      }
    };
    var validatorNumber = function(rule, value, callback) {
      if (value === "" || value == undefined || value == null) {
        callback(new Error("请输入支付宝账号"));
      } else {
        if (
          !/^(?:1[3-9]\d{9}|[a-zA-Z\d._-]*\@[a-zA-Z\d.-]{1,10}\.[a-zA-Z\d]{1,20})$/.test(
            value
          )
        ) {
          callback(new Error("请输入正确的支付宝账号"));
        } else {
          callback();
        }
      }
    };
    var validatorName = function(rule, value, callback) {
      if (value === "" || value == undefined || value == null) {
        callback(new Error("请输入账号姓名"));
      } else {
        if (!/^[\u2E80-\u9FFF]+$/.test(value)) {
          callback(new Error("请输入正确的账号姓名"));
        } else {
          callback();
        }
      }
    };

    return {
      isRead: true,
      frontUrl: "",
      frontUrl2: "",
      addCollection: false,
      baseUrl: global.baseurl,
      uploadImgUrl: global.baseurl + "/api/upload/img",
      form: {
        money: null,
        comment: "",
        id_card: "",
        to_type: 1,
        number: "",
        banknumber: "",
        user_name: "",
        bank: "",
        to_payee: 1,
        front_img: "",
        back_img: "",
        isRead: true
      },
      ruleForm: {
        to_type: [
          { required: true, message: "请选择提现渠道", trigger: "blur" }
        ],
        number: [
          {
            required: true,
            validator: validatorNumber
          }
        ],
        user_name: [{ required: true, validator: validatorName }],
        bank: [{ required: true, message: "请输入支行名称", trigger: "blur" }],
        front_img: [
          { required: true, message: "请上传身份证正面照片", trigger: "blur" }
        ],
        back_img: [
          { required: true, message: "请上传身份证反面照片", trigger: "blur" }
        ],
        to_payee: [
          { required: true, message: "请选择是否默认收款人", trigger: "blur" }
        ],
        id_card: [{ required: true, validator: Validateid_card }],
        banknumber: [{ required: true, validator: validatorBanknumber }]
      }
    };
  },
  components: {
    agreement,
    VCCode
  },
  created () {
    this.form.user_name = this.$store.state.user.name
  },
  methods: {
    // 打开协议
    provision() {
      let roleForm = {
        id_card_number: this.form.id_card,
        bank_card: this.form.number,
        register_bank: this.form.bank
      };
      this.$refs["agreement"].show(roleForm);
    },
    submit(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          if (this.form.isRead) {
            this.$refs['VCCode'].show(this.$store.state.user.phone)
          } else {
            this.$alert("请阅读并同意劳务合同", "提示", {
              confirmButtonText: "确定",
              callback: action => {}
            });
          }
        }
      });
    },
    submitPost() {
      var formData = new FormData();
      formData.append("payee", this.form.user_name);
      formData.append("type", this.form.to_type);
      if (this.form.to_type == 1) {
        formData.append("num", this.form.number);
      } else {
        formData.append("num", this.form.banknumber);
      }
      formData.append("default_payee", this.form.to_payee);
      formData.append("id_card_front", this.form.front_img);
      formData.append("id_card_back", this.form.back_img);
      formData.append("id_card_number", this.form.id_card);
      if (this.form.to_type == 2) {
        formData.append("sub_branch", this.form.bank);
      }
      axios({
        method: "post",
        url: this.baseUrl + "/api/withdrawal",
        data: formData,
        headers: {
          "Content-Type": "multipart/form-data",
          Authorization: "Bearer " + this.$store.state.token
        }
      }).then(res => {
        if (res.data.code == 200) {
          this.$emit('refresh')
          this.$alert("收款账户添加成功", "提示", {
            confirmButtonText: "确定",
            callback: action => {}
          });
          this.frontUrl = "";
          this.frontUrl2 = "";
          this.$emit('refresh')
          this.cancel()
        } else {
          this.$alert(res.data.message, "提示", {
            confirmButtonText: "确定",
            center: true,
            type: "warning",
            callback: action => {}
          });
        }
      });
    },
    cancel () {
      this.addCollection = false;
      this.$refs['ruleForm'].resetFields();
    },
    show() {
      this.addCollection = true;
    },
    toTypeChange(val) {
      if (val == 1) {
      }
    },
    toPayeeChange(val) {
    },
    handleSuccess1(res, file, fileList) {
      if (res.code == 200) {
        this.frontUrl = `${this.baseUrl}/storage/upload/${res.data}`;
        this.form.front_img = file.raw;
      } else {
        this.$alert(res.message, "提示", {
          confirmButtonText: "确定",
          callback: action => {}
        });
      }
    },
    beforeUpload1(file) {
      let that = this;
      let canUpload = true; //是否能够上传（布尔值）
      let type = file.name.substring(file.name.lastIndexOf(".") + 1);
      //不区分大小写
      if (!/jpg|jpeg|png|gif/i.test(type)) {
        that.$message({
          message: "文件格式只能是jpg/jpeg/png/gif",
          type: "warning"
        });
        canUpload = false;
      }
      let size = file.size / 1024 / 1024;
      if (size > 10) {
        that.$message({
          message: "文件大小不能超过10M",
          type: "warning"
        });
        canUpload = false;
      }
      return canUpload;
    },
    handleSuccess2(res, file, fileList) {
      if (res.code == 200) {
        this.frontUrl2 = `${this.baseUrl}/storage/upload/${res.data}`;
        this.form.back_img = file.raw;
      } else {
        this.$alert(res.message, "提示", {
          confirmButtonText: "确定",
          callback: action => {}
        });
      }
    },
    beforeUpload2(file) {
      let that = this;
      let canUpload = true; //是否能够上传（布尔值）
      let type = file.name.substring(file.name.lastIndexOf(".") + 1);
      //不区分大小写
      if (!/jpg|jpeg|png|gif/i.test(type)) {
        that.$message({
          message: "文件格式只能是jpg/jpeg/png/gif",
          type: "warning"
        });
        canUpload = false;
      }
      let size = file.size / 1024 / 1024;
      if (size > 10) {
        that.$message({
          message: "文件大小不能超过10M",
          type: "warning"
        });
        canUpload = false;
      }
      return canUpload;
    }
  }
};
</script>

<style lang='less' type='text/css'>
.add-account {
  /deep/.el-dialog {
    min-width: 600px;
  }
  .tip {
    padding-left: 20px;
  }
  .avatar-uploader {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    width: 200px;
    height: 100px;

    .el-upload:hover {
      border-color: #409eff;
    }
    .avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 200px;
      height: 100px;
      line-height: 100px;
      text-align: center;
    }
    .avatar {
      width: 200px;
      height: 100px;
      display: block;
    }
  }
}
</style>
